<script lang="ts" setup>
import { ref } from 'vue';

import { Page } from '@croco/framework/libraries';

import { service } from '#/api/request';
import { DataTable } from '#/components/data-table';
import { useTable } from '#/views/system/dept/data';

import Edit from './edit.vue';

defineOptions({ name: 'SystemDept' });

const dataTableRef = ref();
const editRef = ref<InstanceType<typeof Edit>>();
const columns = useTable(({ code, scope }) => {
    switch (code) {
        case 'add': {
            onEdit({ parentId: scope.row.id });
            break;
        }
        case 'edit': {
            onEdit(scope.row);
            break;
        }
        case 'remove': {
            onDelete([scope.row]);
            break;
        }
        default: {
            break;
        }
    }
});

function onEdit(data?: any) {
    editRef.value?.open({
        data,
        success: dataTableRef.value?.refresh,
    });
}

// 删除
function onDelete(rows: { id: number; name: string }[]) {
    const names = rows.map((item) => item.name);
    const ids = rows.map((item) => item.id);
    service.confirm({
        message: `确定对部门名称[${names.join(',')}]进行${names.length === 1 ? '删除' : '批量删除'}操作?`,
        url: '/system/dept',
        data: { id: ids },
        success: dataTableRef.value.refresh,
    });
}
</script>

<template>
    <Page auto-content-height>
        <DataTable ref="dataTableRef" :columns="columns" :pagination="false" :default-expand-all="true" api="/system/dept">
            <template #extra>
                <el-button v-auth="'system:dept:add'" @click="onEdit()" />
            </template>
        </DataTable>

        <Edit ref="editRef" />
    </Page>
</template>
